package com.sk.waste.app.views.webview

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.webkit.ConsoleMessage
import android.webkit.WebChromeClient
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity


/**
 * @time 2024/5/20  16:56
 * @author Im_jingwei
 * @desc webview
 */
class LCWebView : WebView {

    constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs) {
        this.set()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(context!!, attrs, defStyle) {
        this.set()
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun set() {
        this.settings.defaultTextEncodingName = "utf-8" // 设置编码
        this.settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING;
//        this.settings.useWideViewPort = true;
//        this.settings.loadWithOverviewMode = true;
        this.settings.javaScriptCanOpenWindowsAutomatically = true
        this.settings.setSupportZoom(true)
        //        this.getSettings().setBuiltInZoomControls(true);
        this.settings.useWideViewPort = true
        this.settings.loadWithOverviewMode = true
        this.settings.cacheMode = WebSettings.LOAD_DEFAULT//LOAD_NO_CACHE
        this.settings.javaScriptEnabled = true
        this.settings.domStorageEnabled = true
        this.settings.allowContentAccess = true; // 是否可访问Content Provider的资源，默认值 true
        this.settings.allowFileAccess = true;    // 是否可访问本地文件，默认值 true
        this.settings.databaseEnabled = true;    // 是否可访问本地文件，默认值 true
        this.settings.builtInZoomControls = true

        this.settings.pluginState = WebSettings.PluginState.ON
//        this.settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        this.webViewClient = FrameWebViewClient()
        this.webChromeClient = AppChromeClient(context as AppCompatActivity)

//        setWebContentsDebuggingEnabled(true);

    }

    private inner class FrameWebViewClient : WebViewClient() {
//        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
//            return try {
//                URL(url)
//                view.loadUrl(url)
//                true
//            } catch (var4: MalformedURLException) {
//                false
//            }
//
//        }

        override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
            // 1. 允许HTTPS/HTTP链接的跳转（淘宝链接均为HTTPS，需包含）
            val url = request.url.toString()
            if (url.startsWith("http:") || url.startsWith("https:")) {
                view.loadUrl(url) // 让WebView继续加载跳转后的链接
                return false // 返回false表示不拦截，由WebView处理
            }
            // 2. 非HTTP/HTTPS协议（如tel://、scheme链接），可根据需求处理
            return super.shouldOverrideUrlLoading(view, request)
        }

        // 可选：监听页面加载错误，打印日志定位问题
        override fun onReceivedError(view: WebView?, request: WebResourceRequest, error: WebResourceError) {
            super.onReceivedError(view, request, error)
            Log.e("LCLOG_WebViewError", "加载失败：" + request.url + "，错误码：" + error.errorCode)
        }

    }

    /**
     * @time 2021/2/26  10:40
     * @author Im_jingwei
     * @desc 注册对象方法到js
     */
    @SuppressLint("JavascriptInterface")
    fun registMethodToJs(any: Any) {
        this.addJavascriptInterface(any, "androidInterface");
    }

    /**
     * @time 2021/2/26  10:43
     * @author Im_jingwei
     * @desc 显示地图
     */
    fun showView(url: String?) {
//        WebJsUtil.getInstance().initJsUtil(this); //初始化地图调用
//        CacheUtile.clearWebviewCache(getContext(), this); //清理缓存
//        String mapUrl = url + "?" + System.currentTimeMillis();
//        Log.d("SKLog_MapUrl",mapUrl);
        this.loadUrl(url!!) //加载在线页面
    }

}